/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kimstore.gui.main;

import com.kimstore.bean.User;
import com.kimstore.factory.DaoFactory;
import com.kimstore.helper.EntityManagerHelper;
import com.kimstore.utilities.Encryption;
import com.kimstore.utilities.Session;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author Administrator
 */
public class Security extends Thread {

    private LogIn login;
    private String username;
    private char[] password;

    public Security(LogIn login) {
        this.login = login;
    }

    @Override
    public void run() {
        try {
            EntityManagerHelper.getConnection().isClosed();

            String username1 = this.username;
            String password2 = Arrays.toString(this.password);

            User currentUser = DaoFactory.getInstance().getUserDao().findByUsernamePassword(username1, password2);

            if (currentUser != null) {
                User user = new User();
                user.setId(currentUser.getId());
                user.setLastLogin(currentUser.getLastLogin());
                user.setPassword(currentUser.getPassword());
                user.setType(currentUser.getType());
                user.setUsername(currentUser.getUsername());

                Session.getInstance().setUser(user);

                currentUser.setLastLogin(new Date());
                DaoFactory.getInstance().getUserDao().saveOrUpdate(currentUser);

                Inventory inventoryWindow = new Inventory();
                inventoryWindow.showWindow();
                login.dispose();
            } else {
                login.hideLoadingLabel();
                JOptionPane.showMessageDialog(login, "Invalid Credentials");
                System.out.println("Invalid Credentials");

                login.enableLogInButton();
            }
        } catch (org.hibernate.exception.SQLGrammarException ex) {
            try {
                String username = "user=" + EntityManagerHelper.getUsername();
                String password = (EntityManagerHelper.getPassword() != null && EntityManagerHelper.getPassword() != "") ? "password=" + EntityManagerHelper.getPassword() : "";
                Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/?" + username + "&" + password);
                Statement s = conn.createStatement();
                int Result = s.executeUpdate("CREATE DATABASE kim_store");

                EntityManagerHelper.configureEntityManagerFactory();

                char[] defaultPassword = "admin".toCharArray();
                DaoFactory.getInstance().getUserDao().saveOrUpdate(new User("admin", Arrays.toString(defaultPassword), User.TYPE_ADMIN));

//                defaultPassword = "adminb".toCharArray();
//                DaoFactory.getInstance().getUserDao().saveOrUpdate(new User("adminb", Arrays.toString(defaultPassword), User.TYPE_ADMIN_B));
//
//                defaultPassword = "stocks".toCharArray();
//                DaoFactory.getInstance().getUserDao().saveOrUpdate(new User("stocks", Arrays.toString(defaultPassword), User.TYPE_STOCKS));
//
//                defaultPassword = "sales".toCharArray();
//                DaoFactory.getInstance().getUserDao().saveOrUpdate(new User("sales", Arrays.toString(defaultPassword), User.TYPE_SALES));
//
//                defaultPassword = "technical".toCharArray();
//                DaoFactory.getInstance().getUserDao().saveOrUpdate(new User("technical", Arrays.toString(defaultPassword), User.TYPE_TECHNICAL));

                String username1 = username;
                String password1 = password;

                User currentUser = DaoFactory.getInstance().getUserDao().findByUsernamePassword(username1, password1);

                if (currentUser != null) {
                    User user = new User();
                    user.setId(currentUser.getId());
                    user.setLastLogin(currentUser.getLastLogin());
                    user.setPassword(currentUser.getPassword());
                    user.setType(currentUser.getType());
                    user.setUsername(currentUser.getUsername());

                    Session.getInstance().setUser(user);

                    currentUser.setLastLogin(new Date());
                    DaoFactory.getInstance().getUserDao().saveOrUpdate(currentUser);

                    Inventory inventoryWindow = new Inventory();
                    login.dispose();
                } else {
                    login.hideLoadingLabel();
                    JOptionPane.showMessageDialog(login, "Invalid Credentials");
                    System.out.println("Invalid Credentials");

                    login.enableLogInButton();
                }

            } catch (SQLException e) {
                Logger.getLogger(LogIn.class.getName()).log(Level.SEVERE, null, e);

                login.enableLogInButton();
            }
        } catch (org.hibernate.exception.GenericJDBCException ex) {
            login.hideLoadingLabel();
            JOptionPane.showMessageDialog(login, "Wrong Database Information. Please contact the\ndevelopers for advice to resolve the problem.");
            //System.exit(1);
            login.enableLogInButton();

        } catch (SQLException ex) {
            Logger.getLogger(LogIn.class.getName()).log(Level.SEVERE, null, ex);
            login.enableLogInButton();
        }
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public char[] getPassword() {
        return password;
    }

    public void setPassword(char[] password) {
        this.password = password;
    }
}
